import time
import cgi
import os

from django.http import HttpResponse, HttpResponseRedirect, HttpResponseServerError
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404
from django import forms
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth import authenticate, login
from django.utils import simplejson

from cetcore.models import Archive, FileEntry, FilePattern#, Photo

def ajax_rating(request):
    print request.POST
    rating = request.POST.get('rating', -1)
    xml = "<ratings><average>%s</average><count>%s</count></ratings>" % (1, rating)
    return HttpResponse(xml, mimetype="text/xml")

def ajax_test2(request):
    print request.POST
    rating = request.POST.get('rating', -1)
    xml = "<ratings><average>%s</average><count>%s</count></ratings>" % (1, rating)
    return HttpResponse(xml, mimetype="text/xml")

def set_value(request, file_id):
    fe = get_object_or_404(FileEntry, pk=file_id)
    params = cgi.parse_qs(request.environ['QUERY_STRING'])
    if params.has_key('archive'):
        fe.place_in_attic()
    return HttpResponseRedirect('/admin/cetcore/fileentry/%s' % file_id)
set_value = staff_member_required(set_value)
#
def process_patterns(request):
    FilePattern.processPatterns()
    return HttpResponseRedirect('/admin/cetcore/')
process_patterns = staff_member_required(process_patterns)

def report(request):
    return render_to_response(
        "admin/cetcore/report.html",
        {'archives' : Archive.objects.all()},
        RequestContext(request, {}),
    )
report = staff_member_required(report)

def index(request):
    return render_to_response(
        "cetcore/index.html",
        {'archives' : Archive.objects.all()},
        RequestContext(request, {}),
    )

def file_details(request, file_id):
    return render_to_response(
        "admin/cetcore/file_details.html",
        {
            'file_entry' : FileEntry.objects.get(id = file_id)
            },
        RequestContext(request, {}),
    )
report = staff_member_required(report)

class UploadFileForm(forms.Form):
    #title = forms.CharField(max_length=50)
    file  = forms.FileField()
    #writable = forms.BooleanField()
    #available = forms.BooleanField()

def handle_uploaded_file(f):
    uploaded_file = "%s_tmp.zip" % int(time.time())
    destination = open(uploaded_file, 'wb+')
    for chunk in f.chunks():
        destination.write(chunk)
    destination.close()
    return uploaded_file

def upload_archive(request):
    do_proceed = False
    form = UploadFileForm()
    if request.method == 'POST':
        if not request.user.is_authenticated():
            username, password = request.POST.get('username', None), request.POST.get('password', None)
            if username and password:
                user = authenticate(username=username, password=password)
                if user is not None:
                    if user.is_active:
                        do_proceed = True
        elif request.user.is_authenticated():
            do_proceed = True

        if do_proceed:
            form = UploadFileForm(request.POST, request.FILES)
            if form.is_valid():
                uploaded_file = handle_uploaded_file(request.FILES['file'])
                archive_id = Archive.process_archive(uploaded_file)
                os.remove(uploaded_file)
                return HttpResponseRedirect('/admin/cetcore/archive/%s' % archive_id)
        else:
            return render_to_response('admin/cetcore/upload_archive.html', {'form': form}) 
    return render_to_response('admin/cetcore/upload_archive.html', {'form': form})
    
def ajax_test(request):
    to_return = {'msg':u'Dung.' }
    serialized = simplejson.dumps(to_return)
    return HttpResponse(serialized, mimetype="application/json")
